import axios from 'axios'
import router from '@/router/index'

import { dynamicRouter } from '@/router/dynamicRouter2'
import { staticRouter, errorRouter } from '@/router/staticRouter'

// 用户模块
export const userAuth = {
  namespaced: true, // 使用命名空间
  state: {
    authMenus: [],
    authButtons: [],
    userFinallyMenus: [...staticRouter, ...errorRouter]
  },
  mutations: {
    SET_AUTH_MENUS(state, authMenus) {
      state.authMenus = [...authMenus]
    },
    SET_AUTH_BUTTONS(state, authButtons) {
      state.authButtons = authButtons
    },
    SET_USER_FINALLY_MENUS(state, userFinallyMenus) {
      state.userFinallyMenus = [...state.userFinallyMenus, ...userFinallyMenus]
    },
    ClEAR_USER_FINALLY_MENUS(state, menus) {
      state.userFinallyMenus = menus
    }
  },
  actions: {
    async getAuthMenus({ commit }) {
      try {
        const response = await axios.get('http://127.0.0.1:4523/m1/5702810-5383946-default/api/auth1')
        // 过滤路由
        let finallyRoutes = filterRouter(response.data.roles, dynamicRouter)
        commit('SET_USER_FINALLY_MENUS', finallyRoutes)
        finallyRoutes.forEach(route => {
          router.addRoute(route)
        })
        //
      } catch (error) {
        console.error('Error fetching users:', error)
      }
    },
    async getAuthButton({ commit }) {
      try {
        const response = await axios.get('https://jsonplaceholder.typicode.com/users')
        commit('SET_AUTH_BUTTONS', response.data)
      } catch (error) {
        console.error('Error fetching users:', error)
      }
    }
  }
}

function filterRouter(userAuth, dynamicRouter) {
  // 遍历动态路由的每一项
  return dynamicRouter.filter(route => {
    // 判断路由是否存在权限要求
    if (route.meta && route.meta.requiresRole) {
      // 对比用户权限得到过滤后的路由
      const hasAccess = route.meta.requiresRole.some(role => userAuth.includes(role))
      // 过滤子路由将子路由作为新对象属性
      if (hasAccess && route.children) {
        route.children = filterRouter(userAuth, route.children)
      }
      // 返回最终路由
      return hasAccess
    }
    return true
  })
}
